package com.example.sunmiv1.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;

import com.example.sunmiv1.R;
import com.example.sunmiv1.adapter.AllocationAdapter;
import com.example.sunmiv1.entity.AllocationListInfo;
import com.example.sunmiv1.entity.AllocationType;
import com.example.sunmiv1.entity.StoreInfo;
import com.example.sunmiv1.utils.LogUtil;
import com.example.sunmiv1.utils.Tools;
import com.example.sunmiv1.utils.net.ACache;
import com.example.sunmiv1.utils.net.Common;
import com.example.sunmiv1.utils.net.GsonUtils;
import com.example.sunmiv1.utils.net.HttpUtils;
import com.example.sunmiv1.utils.net.LoadingDialog;
import com.example.sunmiv1.utils.net.TextCallBack;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

// 出庫單
public class StoreAllocationActivity extends Activity {
    @BindView(R.id.title_back)
    ImageView titleBack;
    @BindView(R.id.title_title)
    TextView titleTitle;
    @BindView(R.id.end_allocation)
    RadioButton endAllocation;
    @BindView(R.id.not_allocation)
    RadioButton notAllocation;
    @BindView(R.id.startTime_allocation)
    TextView startTimeAllocation;
    @BindView(R.id.endTime_allocation)
    TextView endTimeAllocation;
    @BindView(R.id.edit_allocation)
    EditText editAllocation;
    @BindView(R.id.search_allocation)
    ImageView searchAllocation;
    @BindView(R.id.add_allocation)
    Button addAllocation;
    @BindView(R.id.listView_allocation)
    PullToRefreshListView listViewAllocation;
    @BindView(R.id.spinner_allocation_type)
    Spinner spinnerAllocationType;
    @BindView(R.id.linear_is_allocation)
    LinearLayout linearIsAllocation;
    @BindView(R.id.spinner_supplier)
    Spinner spinnerSupplier;
    @BindView(R.id.btn_to_top)
    ImageView btnToTop;
    private Context context;
    private LoadingDialog loadingDialog;
    private ACache aCache;
    private Intent intent;

    private int page = 1;
    public String warehousing_status = "";//0.未入庫 1.已入庫
    private List<AllocationListInfo.DataBean> list = new ArrayList<>();
    private List<AllocationType.DataBean> typeList = new ArrayList<>();
    private List<StoreInfo.StoreSupplierBean> storeSupplierList = new ArrayList<>();//門店供應商
    private List<StoreInfo.SupplierBean> supplierList = new ArrayList<>();//商戶供應商
    private AllocationListInfo allocationListInfo;
    private AllocationAdapter allocationAdapter;
    private StoreInfo storeInfo;

    private String type = "";//出庫類型
    private String supplierId = "";//商戶供應商
    private String storeSupplierId = "";// 門店供應商
    private String userType;// 用戶類型  1：商戶  2：店長

    private int firstCeate = 0;

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    page++;
                    setAllocationAdapter();
                    break;
                case 2:
                    setAllocationAdapter();
                    break;
                case 3:
                    storeSupplierList.clear();
                    if ("2".equals(userType)) {
                        storeSupplierList.add(new StoreInfo.StoreSupplierBean("", "所有供貨商"));
                    }
                    for (StoreInfo.StoreSupplierBean storeSupplierBean : storeInfo.getStoreSupplier()) {
                        storeSupplierList.add(storeSupplierBean);
                    }
                    if (storeSupplierList.size() > 0) {
                        List<String> arrayList = new ArrayList<>();

                        for (int i = 0; i < storeSupplierList.size(); i++) {
                            String name = storeSupplierList.get(i).getSupplier_name();
                            arrayList.add(name);
                        }

                        //往會員來源Spinner中添加數據
                        ArrayAdapter<String> adapter = new ArrayAdapter<String>(context, R.layout.spinner_item, arrayList);  //創建一個數組適配器
                        adapter.setDropDownViewResource(R.layout.dropdown_stytle);
                        spinnerSupplier.setAdapter(adapter);

                    }
                    supplierList.clear();
                    if ("1".equals(userType)) {
                        supplierList.add(new StoreInfo.SupplierBean("", "所有供貨商"));
                    }
                    for (StoreInfo.SupplierBean supplierBean : storeInfo.getSupplier()) {
                        supplierList.add(supplierBean);
                    }
                    if (supplierList.size() > 0) {
                        List<String> arrayList = new ArrayList<>();

                        for (int i = 0; i < supplierList.size(); i++) {
                            String name = supplierList.get(i).getSupplier_name();
                            arrayList.add(name);
                        }
                        //往會員來源Spinner中添加數據
                        ArrayAdapter<String> adapter = new ArrayAdapter<String>(context, R.layout.spinner_item, arrayList);  //創建一個數組適配器
                        adapter.setDropDownViewResource(R.layout.dropdown_stytle);
                        spinnerSupplier.setAdapter(adapter);
                    }
                    break;
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_store_allocation);
        ButterKnife.bind(this);
        titleTitle.setText(R.string.storeAllocation1);
        context = this;
        aCache = ACache.get(context);
        userType = aCache.getAsString("userType");
        loadingDialog = new LoadingDialog(context);
        getAllocationType();
        getSupplier();
        initListener();
    }

    @Override
    protected void onResume() {
        super.onResume();
//        endAllocation.setChecked(false);
//        notAllocation.setChecked(true);
        page = 1;
        if ("1".equals(userType)) {
            getMerchantAllocateOrder();
        } else if ("2".equals(userType)) {
            getAllocateOrder();
        }
    }

    private void initListener() {
        listViewAllocation.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                page = 1;
                list.clear();
                setAllocationAdapter();
                if ("1".equals(userType)) {
                    getMerchantAllocateOrder();
                } else if ("2".equals(userType)) {
                    getAllocateOrder();
                }
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                if ("1".equals(userType)) {
                    getMerchantAllocateOrder();
                } else if ("2".equals(userType)) {
                    getAllocateOrder();
                }
            }
        });
        notAllocation.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                warehousing_status = "0";
                page = 1;
                list.clear();
                setAllocationAdapter();
                if ("1".equals(userType)) {
                    getMerchantAllocateOrder();
                } else if ("2".equals(userType)) {
                    getAllocateOrder();
                }
            }
        });
        endAllocation.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                warehousing_status = "1";
                page = 1;
                list.clear();
//                setAllocationAdapter();
                if ("1".equals(userType)) {
                    getMerchantAllocateOrder();
                } else if ("2".equals(userType)) {
                    getAllocateOrder();
                }
            }
        });
        /*選擇出庫類型*/
        spinnerAllocationType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (0 == position && 0 == firstCeate) {
                    firstCeate = 1;
                    return;
                }
                type = typeList.get(position).getId();
                warehousing_status = "0";
                if ("1".equals(userType)) {
                    if (type.equals("4")) {
                        spinnerSupplier.setVisibility(View.VISIBLE);
                    } else {
                        spinnerSupplier.setVisibility(View.INVISIBLE);
                    }
                    if (type.equals("1")) {// 調撥  有出庫類型選擇
                        linearIsAllocation.setVisibility(View.VISIBLE);
                        notAllocation.setChecked(true);
                        endAllocation.setChecked(false);
                    } else {
                        linearIsAllocation.setVisibility(View.GONE);
                    }
                    if ("3".equals(type)) {
                        warehousing_status = "";
                        allocationAdapter.putType(type);
                    }
                } else if ("2".equals(userType)) {
                    if (type.equals("3") || type.equals("1")) {// 調撥|向商戶退貨  有出庫類型選擇
                        linearIsAllocation.setVisibility(View.VISIBLE);
                        notAllocation.setChecked(true);
                        endAllocation.setChecked(false);
                    } else {
                        linearIsAllocation.setVisibility(View.GONE);
                    }
                    if (type.equals("9")) {
                        spinnerSupplier.setVisibility(View.VISIBLE);
                    } else {
                        spinnerSupplier.setVisibility(View.INVISIBLE);
                    }
                }
                page = 1;
                list.clear();
                if ("1".equals(userType)) {
                    getMerchantAllocateOrder();
                } else if ("2".equals(userType)) {
                    getAllocateOrder();
                }
//                setAllocationAdapter();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        /*9向供貨商退貨出庫選擇供貨商*/
        spinnerSupplier.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (0 == position) {
                    return;
                }
                if (supplierList.size() > 0) {
                    supplierId = supplierList.get(position).getId();//商戶供應商
                }
                if (storeSupplierList.size() > 0) {
                    storeSupplierId = storeSupplierList.get(position).getId();//門店供應商
                }
                page = 1;
                list.clear();
                setAllocationAdapter();
                if ("1".equals(userType)) {
                    getMerchantAllocateOrder();
                } else if ("2".equals(userType)) {
                    getAllocateOrder();
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }

    @OnClick({R.id.title_back, R.id.btn_to_top, R.id.startTime_allocation, R.id.endTime_allocation, R.id.search_allocation, R.id.add_allocation})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                finish();
                break;
            case R.id.startTime_allocation:
                Tools.getDateFromDatePickerDialog(startTimeAllocation);
                if ("1".equals(userType)) {
                    getMerchantAllocateOrder();
                } else if ("2".equals(userType)) {
                    getAllocateOrder();
                }
                break;
            case R.id.endTime_allocation:
                Tools.getDateFromDatePickerDialog(endTimeAllocation);
                if ("1".equals(userType)) {
                    getMerchantAllocateOrder();
                } else if ("2".equals(userType)) {
                    getAllocateOrder();
                }
                break;
            case R.id.search_allocation:
                page = 1;
                list.clear();
                setAllocationAdapter();
                if ("1".equals(userType)) {
                    getMerchantAllocateOrder();
                } else if ("2".equals(userType)) {
                    getAllocateOrder();
                }
                break;
            case R.id.add_allocation://新增出庫單
                intent = new Intent(context, AddAllocationActivity.class);
                intent.putExtra("AlloOrOut", "out");
                startActivity(intent);
                break;
            case R.id.btn_to_top:
                listViewAllocation.getRefreshableView().setSelection(0);
                break;
        }
    }

    private void setAllocationAdapter() {
        LogUtil.i("type:" + type);
        if (allocationAdapter == null) {
            allocationAdapter = new AllocationAdapter(context, list, type);
            listViewAllocation.setAdapter(allocationAdapter);
        } else {
            allocationAdapter.notifyDataSetChanged();
        }
    }

    /*獲取出庫類型0其他出庫   1向商戶退貨出庫  2盤虧出庫  3調撥出庫  9向供貨商退貨出庫*/
    private void getAllocationType() {
        typeList.clear();
        typeList.add(new AllocationType.DataBean("", "全部出庫類型"));
        typeList.add(new AllocationType.DataBean("0", "其他出庫"));
        if ("1".equals(userType)) {
            typeList.add(new AllocationType.DataBean("1", "調撥出庫"));
            typeList.add(new AllocationType.DataBean("2", "盤虧出庫"));
            typeList.add(new AllocationType.DataBean("3", "門店申請調撥出庫"));
            typeList.add(new AllocationType.DataBean("4", "退貨出庫"));
        } else if ("2".equals(userType)) {
            typeList.add(new AllocationType.DataBean("1", "向商戶退貨出庫"));
            typeList.add(new AllocationType.DataBean("2", "盤虧出庫"));
            typeList.add(new AllocationType.DataBean("3", "調撥出庫"));
            typeList.add(new AllocationType.DataBean("9", "向供貨商退貨出庫"));
        }


        if (typeList.size() > 0) {
            List<String> arrayList = new ArrayList<>();

            for (int i = 0; i < typeList.size(); i++) {
                String name = typeList.get(i).getType();
                arrayList.add(name);
            }

            //往會員來源Spinner中添加數據
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(context, R.layout.spinner_item, arrayList);  //創建一個數組適配器
            adapter.setDropDownViewResource(R.layout.dropdown_stytle);
            spinnerAllocationType.setAdapter(adapter);

        }
    }

    /*獲取門店出庫*/
    private void getAllocateOrder() {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("start_time", startTimeAllocation.getText().toString().trim());
            jsonObject.put("end_time", endTimeAllocation.getText().toString().trim());
            jsonObject.put("storeid", aCache.getAsString("storeid"));
            jsonObject.put("merchantid", aCache.getAsString("merchantid"));
            if ("1".equals(userType) || "2".equals(userType)) {
                jsonObject.put("operator_id", aCache.getAsString("operator_id"));
            } else {
                jsonObject.put("operator_id", aCache.getAsString("uid"));
            }
            jsonObject.put("user_type", userType);
            jsonObject.put("order_number", editAllocation.getText().toString().trim());
            jsonObject.put("warehousing_status", warehousing_status);
            jsonObject.put("page", page);
            jsonObject.put("type", type);
            if (type.equals("9")) {
                jsonObject.put("supplier_id", storeSupplierId);
            } else {
                jsonObject.put("supplier_id", "");
            }
            jsonObject.put("limit", 20);
            HttpUtils.post(context, Common.STORE_ALLOCATION, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    loadingDialog.dismiss();
                    listViewAllocation.onRefreshComplete();
                    allocationListInfo = GsonUtils.JsonToBean(text, AllocationListInfo.class);
                    Message msg = new Message();
                    if (allocationListInfo.getStatus() == 1) {
                        if (page == 1)
                            list.clear();
                        list.addAll(allocationListInfo.getData());
                        msg.what = 1;
                    } else {
                        msg.what = 2;
                    }
                    handler.sendMessage(msg);
                }

                @Override
                protected void onFailure(ResponseException e) {
                    loadingDialog.dismiss();
                    listViewAllocation.onRefreshComplete();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /*獲取商戶出庫*/
    private void getMerchantAllocateOrder() {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("start_time", startTimeAllocation.getText().toString().trim());
            jsonObject.put("end_time", endTimeAllocation.getText().toString().trim());
            jsonObject.put("storeid", aCache.getAsString("storeid"));
            jsonObject.put("merchantid", aCache.getAsString("merchantid"));
            if ("1".equals(userType) || "2".equals(userType)) {
                jsonObject.put("operator_id", aCache.getAsString("operator_id"));
            } else {
                jsonObject.put("operator_id", aCache.getAsString("uid"));
            }
            jsonObject.put("user_type", userType);
            jsonObject.put("order_number", editAllocation.getText().toString().trim());
            jsonObject.put("warehousing_status", warehousing_status);
            jsonObject.put("page", page);
            jsonObject.put("type", type);
            if (type.equals("4")) {
                jsonObject.put("supplier_id", supplierId);
            } else {
                jsonObject.put("supplier_id", "");
            }
            jsonObject.put("limit", 20);
            HttpUtils.post(context, Common.ALLOCATE_ORDER, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {

                    listViewAllocation.onRefreshComplete();
                    Gson gson = new Gson();
                    allocationListInfo = gson.fromJson(text, AllocationListInfo.class);
//                    allocationListInfo = GsonUtils.JsonToBean(text, AllocationListInfo.class);
                    loadingDialog.dismiss();
                    Message msg = new Message();
                    if (allocationListInfo.getStatus() == 1) {
                        if (page == 1)
                            list.clear();
                        list.addAll(allocationListInfo.getData());
                        msg.what = 1;
                    } else {
                        msg.what = 2;
                    }
                    handler.sendMessage(msg);
                }

                @Override
                protected void onFailure(ResponseException e) {
                    loadingDialog.dismiss();
                    listViewAllocation.onRefreshComplete();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /*獲取供應商（在type爲"9"的時候“向供貨商退貨出庫”*/
    private void getSupplier() {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("storeid", aCache.getAsString("storeid"));
            jsonObject.put("merchantid", aCache.getAsString("merchantid"));
            jsonObject.put("user_type", userType);
            HttpUtils.post(context, Common.STORE_SUPPLIER, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    loadingDialog.dismiss();
                    listViewAllocation.onRefreshComplete();
                    Gson gson = new Gson();
                    storeInfo = GsonUtils.JsonToBean(text, StoreInfo.class);
                    Message msg = new Message();
                    if (storeInfo.getStatus() == 1) {
                        msg.what = 3;
                    } else {

                    }
                    handler.sendMessage(msg);
                }

                @Override
                protected void onFailure(ResponseException e) {
                    loadingDialog.dismiss();
                    listViewAllocation.onRefreshComplete();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否則所有的組件都不會有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);

    }

    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //獲取輸入框當前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 點擊的是輸入框區域，保留點擊EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

}
